package org.jason.mapmaker.server.repository.jpa;

import org.jason.mapmaker.model.Feature;
import org.jason.mapmaker.server.repository.FeatureRepository;
import org.jason.mapmaker.shared.exceptions.RepositoryException;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import java.io.Serializable;
import java.util.logging.Logger;

/**
 * JPA implementation of FeatureRepository interface
 *
 * This class does NOT extend Spring's JpaTemplate in order to reduce coupling on Spring. 
 *
 * @author Jason Ferguson
 */
@Repository("featureRepository")
public class JpaFeatureRepository implements FeatureRepository {

    private static final Logger log = Logger.getLogger(JpaFeatureRepository.class.getName());

    private EntityManagerFactory entityManagerFactory;

    @PersistenceUnit
    public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
        this.entityManagerFactory = entityManagerFactory;
    }

    public void persist(Feature object) throws RepositoryException {

        EntityManager em = entityManagerFactory.createEntityManager();

        try {
            // get a transaction, persist the object, then commit
            em.getTransaction().begin();
            em.persist(object);
            em.getTransaction().commit();

        } catch (EntityExistsException ex) {
            // need to log this somehow
            log.warning("persist() threw EntityExistsException: " + ex.getMessage());

            throw new RepositoryException(ex);
        } finally {
            em.close();
        }
    }

    public void remove(Feature object) throws RepositoryException {

        EntityManager em = entityManagerFactory.createEntityManager();

        try {
            // get a transaction, remove the object, then commit
            em.getTransaction().begin();
            em.remove(object);
            em.getTransaction().commit();

        } catch (Exception ex) {
            log.warning("remove() threw Exception: " + ex.getMessage());
            throw new RepositoryException(ex);
        } finally {
            em.close();
        }
    }

    public Feature getById(Serializable uniqueIdentifer) {
        throw new UnsupportedOperationException();
    }
}
